
import os
from flask import Flask, request, redirect, render_template, url_for, flash, send_from_directory
from werkzeug.utils import secure_filename

# 修改为Nginx的服务目录
UPLOAD_FOLDER = os.environ.get('UPLOAD_FOLDER', '/usr/share/nginx/html')
ALLOWED_EXTENSIONS = {'html'}
CLASS_SECRET_CODE = "szpt2025cloud"

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 2 * 1024 * 1024
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SECRET_KEY'] = 'a_strong_secret_key'

os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/')
def upload_form():
    return render_template('upload.html')

@app.route('/wall')
def resume_wall():
    try:
        all_files = os.listdir(app.config['UPLOAD_FOLDER'])
        html_files = sorted([f for f in all_files if f.endswith('.html')])

        # 使用Nginx服务器地址
        nginx_base_url = "http://192.168.200.10:8060"

        return render_template('wall.html', resumes=html_files, nginx_base_url=nginx_base_url)
    except FileNotFoundError:
        return render_template('wall.html', resumes=[], nginx_base_url="")

@app.route('/upload', methods=['POST'])
def upload_file():
    if request.form.get('secret_code') != CLASS_SECRET_CODE:
        flash('班级口令错误！')
        return redirect(url_for('upload_form'))

    if 'file' not in request.files or not request.form.get('student_name'):
        flash('姓名和文件不能为空')
        return redirect(request.url)

    file = request.files['file']
    student_name = request.form.get('student_name').strip()

    if file and allowed_file(file.filename):
        final_filename = f"{student_name}.html".replace('/', '').replace('\\', '')
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], final_filename)

        if os.path.exists(file_path):
            flash(f"错误：'{student_name}' 的简历已存在！")
            return redirect(url_for('upload_form'))

        try:
            file.save(file_path)
            # 设置文件权限，确保Nginx可以读取
            os.chmod(file_path, 0o644)
        except PermissionError:
            flash("上传失败：目录无写入权限，请联系管理员！")
            return redirect(url_for('upload_form'))

        wall_url = "http://192.168.200.10:8060/wall"
        return f"上传成功！<a href='{wall_url}' target='_blank'>点击查看简历墙</a>。<br><a href='/'>返回上传</a>"

    flash('仅允许上传 .html 格式的文件')
    return redirect(request.url)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
